<?php

namespace App\Http\Controllers\Api\V1;

use Carbon\Carbon;
use App\Models\AppleTree;
use App\Models\AppleTreesRecord;
use Illuminate\Support\Facades\Cache;
use App\Services\MakeAppleTreeRecords\MakeAppleTreeRecords;
use App\Services\MakeAppleTreeRecords\MakeAppleTreeRecordsRequest;
use App\Http\Controllers\Api\V1\Resources\AppleTreeRecordsResource;
use App\Http\Controllers\Api\V1\Resources\AppleTreeResource;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;



class AppleTreesController extends Controller
{
	

	public function store()
	{

		$lock = Cache::lock('buy_apple_trees', 1);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');

			$request = app(MakeAppleTreeRecordsRequest::class);

			$vipPurchase = app(MakeAppleTreeRecords::class, [
				'user' => request()->user(),
				'tree' => $request->tree(),
			])->apply();

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}

	public function index()
	{
		
		$user = request()->user();
		$appleTrees  = AppleTree::query()->orderBy('id')->get();
		return ['data' =>  AppleTreeResource::collection($appleTrees)];
	}

	public function records()
	{
		$user = request()->user();
		$appleTreesRecord  = $user->appleTreeRecords()->where("expired_at",">",Carbon::now())->orderBy('id')->paginate();

		return AppleTreeRecordsResource::collection($appleTreesRecord);
	}
}
